﻿/****************************************************************************
*                                                                           *
* Copyright (c) (RSC) Ionescu M. Marius. All rights reserved(2010).         *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using NS_Controls;
using System.Collections;
using AjaxControlToolkit;
using System.Drawing;
using System.Web.UI.HtmlControls;

public partial class SearchPage : SessionControlBase
{
    public int totalRows
    {
        get { return (int)(this.ViewState["totalRows"] ?? 1); }
        set { this.ViewState["totalRows"] = value; }
    }
	public int perPage
	{
		get { return (int)(this.ViewState["perPage"] ?? 10); }
		set { this.ViewState["perPage"] = value; }
	}
	public int pageCount
	{
		get { return (int)Math.Ceiling(totalRows / (double)perPage); }
	}

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
    }

    public void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack)
            {
				CreateLinkButtons();
            }

			txtSearch.Attributes.Add("onkeydown", @"
				if(event.which || event.keyCode)
					if ((event.which == 13) || (event.keyCode == 13))
					{
						document.getElementById('" + btnSearch.ClientID + @"_btn').click();
						return false;
					}
				return true;");
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    private void LoadData()
    {
        try
        {
            DataSet ds_PacientSearch = Hipocrate.DB.DBConnection.GetData("Pacient_SearchSimple", new string[] { "strDescription" }, new object[] { txtSearch.Text });
            DataView dv = ds_PacientSearch.Tables[0].DefaultView;
			totalRows = dv.Count;

            DataSet ds_SystemConfig = GetSystemConfigDataSet();
            DataView dv1 = new DataView(ds_SystemConfig.Tables[0]);
            dv1.RowFilter = "Code = 'Sectiuni pe pagina'";
            perPage = Convert.ToInt32(dv1[0]["Name"]);

			CreateLinkButtons(); 

			int[] pages = GetPageNumbersArray();
            if (CurrentPage >= pages.Length)
                CurrentPage = 0;

            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = dv;
            objPds.AllowPaging = true;
            objPds.PageSize = perPage;
            objPds.CurrentPageIndex = CurrentPage;
            cmdPrev.Enabled = !objPds.IsFirstPage;
            cmdNext.Enabled = !objPds.IsLastPage;
            rptPacientSearch.DataSource = objPds;
            rptPacientSearch.DataBind();
            lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
                + objPds.PageCount.ToString();

        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void btnPacientNew_Click(object sender, EventArgs e)
    {
        try
        {
			Page.Response.Redirect("~/Pages/Hipocrate/Pacient.aspx?action=new", false);
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, false);
        }
    }

    protected void btnsearch_Click(object sender, EventArgs e)
    {
        try
        {
            LoadData();
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    private DataSet GetSystemConfigDataSet()
    {
        DataSet ds_SystemConfig = (DataSet)Session["ds_SystemConfig"];
        if (ds_SystemConfig == null)
        {
            ds_SystemConfig = Hipocrate.DB.DBConnection.GetData("System_Config_Select", new string[] { }, new object[] { });
            Session["ds_SystemConfig"] = ds_SystemConfig;
        }
        return ds_SystemConfig;
    }

    private void CreateLinkButtons()
    {
        try
        {
            DataSet ds_SystemConfig = GetSystemConfigDataSet();
            DataView dv = new DataView(ds_SystemConfig.Tables[0]);
            dv.RowFilter = "Code = 'Sectiuni pe pagina'";

            tblPagination.Controls.Clear();

			int[] pages = GetPageNumbersArray();
            if (pages.Length == 1) return; // no pagination required

			TableRow tblRowPag = new TableRow();
			TableCell tblCellPag = new TableCell();
			
			tblCellPag.Wrap = false;
			tblCellPag.CssClass = "tdn_perfect";
			tblCellPag.Controls.Add(new LiteralControl("Pagina: "));

			tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
			tblCellPag.Controls.Add(NewLinkButton("linkFst", false, "|&lt;", "First", 0));
			tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));

            if (pages.Length > perPage)
            {
                CreatePaginationLinks(ref tblCellPag, 0, 4);
                tblCellPag.Controls.Add(NewSeparator());
                if (5 < CurrentPage - 5)
                {
                    tblCellPag.Controls.Add(new LiteralControl("..."));
                    tblCellPag.Controls.Add(NewSeparator());
                }
                CreatePaginationLinks(ref tblCellPag, Math.Max(5, CurrentPage - 5), Math.Min(CurrentPage + 5, pages.Length - 1));
                tblCellPag.Controls.Add(NewSeparator());
                if (CurrentPage + 6 < pages.Length - 5)
                {
                    tblCellPag.Controls.Add(new LiteralControl("...")); tblCellPag.Controls.Add(NewSeparator());
                }
                CreatePaginationLinks(ref tblCellPag, Math.Max(CurrentPage + 6, pages.Length - 5), pages.Length - 1);
            }
            else
                CreatePaginationLinks(ref tblCellPag, 0, pages.Length - 1);

            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            tblCellPag.Controls.Add(NewLinkButton("linkLst", false, "&gt;|", "Last", 0));
            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));

            tblCellPag.Controls.Add(new LiteralControl(" din " + pages.Length));

            tblRowPag.Cells.Add(tblCellPag);
            tblPagination.Rows.Add(tblRowPag);
        }

        catch (Exception ex)
        {
			this.SetMessage(ex.Message, true);
        }
    }

	private LiteralControl NewSeparator()
	{
		return new LiteralControl("  &middot;  ");
	}

	private void CreatePaginationLinks(ref TableCell target, int firstPage, int lastPage)
	{
		for (int k = firstPage; k <= lastPage; ++k)
		{
			if (k > firstPage) target.Controls.Add(NewSeparator());
			target.Controls.Add(NewLinkButton("link" + (k + 1).ToString(), CurrentPage == k, (k + 1).ToString(), "Numbered", k));
		}
	}
	private LinkButton NewLinkButton(string id, bool disabled, string text, string cmdName, int cmdArgument)
	{
		LinkButton result = new LinkButton();
		result.ID = id;
		result.CssClass = "aLink";
		result.Style.Add("text-decoration", "none");
		result.Font.Bold = disabled;
		result.Enabled = !disabled;
		result.Text = text;
		result.CausesValidation = false;
		result.Command += new CommandEventHandler(NavigationLink_Click);
		result.CommandName = cmdName;
		result.CommandArgument = cmdArgument.ToString();
		return result;
	}

    void NavigationLink_Click(Object sender, CommandEventArgs e)
    {
        try
        {
            switch (e.CommandName)
            {
                case "First": CurrentPage = 0;
                    break;
				case "Last": CurrentPage = (int)Math.Ceiling((double)pageCount / perPage) - 1;
                    break;
                case "Next": CurrentPage = CurrentPage + 1;
                    break;
                case "Prev": CurrentPage = CurrentPage - 1;
                    break;
                case "Numbered":
                    CurrentPage = Int32.Parse(e.CommandArgument.ToString());
                    break;
				default:
					return;
            }
			LoadData();
		}
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    public int[] GetPageNumbersArray()
    {
        int totalPages = pageCount;
        int[] pg = new int[totalPages];

		for (int k = 0; k < totalPages; k++)
			pg[k] = k + 1;

        return pg;
    }

    public int CurrentPage
    {
        get
        {
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    protected void cmdPrev_Click(object sender, System.EventArgs e)
    {
		if (CurrentPage > 0)
			--CurrentPage;
        LoadData();
    }

	protected void cmdNext_Click(object sender, System.EventArgs e)
	{
        ++CurrentPage;
		LoadData();
	}

	protected string DisplayGender(object fromDB)
	{
		if (fromDB == DBNull.Value)
			return "?";
		if ((bool)fromDB)
			return "M";
		else
			return "F";
	}

	protected string FixAge(object fromDB)
	{
		if (fromDB == DBNull.Value)
			return "?";
		if (System.Convert.ToInt32(fromDB) == 1)
			return "1 an";
		return fromDB + " ani";
	}
}
